<template>
  <div class="single-media">
    <div class="video-container">
      <div class="info" v-if="false">
        <span class="ir-rule" :class="{ active: isLabel }">{{
          `IR规则【${isLabel ? '已激活' : '未激活'}】`
        }}</span>
        <span class="websocket"
          >WebSocket Server
          {{ `【${connectionStatus ? '已连接' : '未连接'}】` }}</span
        >
      </div>
      <div class="video-block-container">
        <EasyPlayerPro
          ref="easyPlayerPro"
          class="video-block"
          :videoObject="currentVideo"
          :key="currentVideo.id"
          :isLabel="isLabel"
        ></EasyPlayerPro>
        <CustomPlayer
          v-if="false"
          class="video-block"
          :videoObject="currentVideo"
          :key="currentVideo.id"
          :isLabel="isLabel"
        ></CustomPlayer>
      </div>
    </div>
    <div class="charts-container">
      <!-- 可以切换实时和当天的曲线，两个切换并排 -->
      <div class="charts-mode">
        <span
          class="charts-mode-item item1"
          :class="{ active: mode === 0 }"
          @click="setMode(0)"
          >实时</span
        >
        <span
          class="charts-mode-item item2"
          :class="{ active: mode === 1 }"
          @click="setMode(1)"
          >当天</span
        >
      </div>
      <div class="charts-item">
        <graph-echarts class="charts" :options="tempOptions"></graph-echarts>
      </div>
      <div class="charts-item">
        <graph-echarts class="charts" :options="uvOptions"></graph-echarts>
      </div>
    </div>
    <!-- 音频，当告警触发时，播放本段音频 -->
    <div class="audio-container" v-show="audioPlaying" v-if="false"></div>
    <audio ref="audioPlayer" src="@/assets/alarm.mp3"></audio>
  </div>
</template>

<script>
import { getWebsocketMessage } from '@/api/camera';
import GraphEcharts from './GraphECharts.vue';
// import VideoBlock from './VideoBlock.vue';
// <video-block class="video-block" :videoObject="currentVideo"></video-block>
import CustomPlayer from '@/components/CustomPlayer/index.vue';
import EasyPlayerPro from '@/components/EasyPlayerPro/index.vue';
export default {
  name: 'SingleMedia',
  components: { GraphEcharts, EasyPlayerPro, CustomPlayer },
  data() {
    return {
      tempOptions: {
        series: [],
      },
      uvOptions: {
        series: [],
      },
      // 是否可以标注
      isLabel: false,
      wsMessages: [],
      // 0: 实时，1: 当天
      mode: 0,
      // audioPlaying: false
    };
  },
  // created() {
  //   this.setTempOptions();
  //   this.setUVOptions();
  // },
  // destroyed() {
  //   if (this.$store.getters['websocketClient/socket']) {
  //     this.$store.dispatch('websocketClient/close');
  //   }
  // },
  computed: {
    // 当前播放的视频
    currentVideo() {
      return this.$store.getters['playVideo/getCurrentPlayingVideo'];
    },
    // 配置信息
    config() {
      return this.$store.getters['websocketClient/config'];
    },
    // 连接状态
    connectionStatus() {
      return this.$store.getters['websocketClient/isConnected'](
        `${process.env.VUE_APP_WEBSOCKET_URL}/${this.currentVideo.cameraId}`
      );
    },
    messages() {
      const messages = this.$store.getters['websocketClient/messages'](
        `${process.env.VUE_APP_WEBSOCKET_URL}/${this.currentVideo.cameraId}`
      );
      // messages的json串转为json数组
      const newMessages = [];
      messages.forEach((item) => {
        const message = JSON.parse(item);
        if (
          message.cameraId === this.currentVideo.cameraId &&
          message.command === this.config['btnCommand']['temperatureAnduvData']
        ) {
          newMessages.push(message.data);
        }
      });
      // 只保留最近的60条消息
      if (newMessages.length > 60) {
        newMessages.splice(0, newMessages.length - 60);
      }
      return newMessages;
    },
  },
  watch: {
    currentVideo: {
      handler(newVideo) {
        if (newVideo) {
          this.mode = 0;
        }
      },
    },
    mode: {
      async handler(newMode) {
        let date, t_data, uv_data;
        if (newMode === 0) {
          date = this.messages.map((item) => {
            return item.date.split(' ')[1];
          });
          t_data = this.messages.map((item) => {
            return item.temperature;
          });
          uv_data = this.messages.map((item) => {
            return item.uv;
          });
        } else {
          await this.getWsMessages();
          date = this.wsMessages.map((item) => {
            return item.date.split(' ')[1];
          });
          t_data = this.wsMessages.map((item) => {
            return item.ir_temperature;
          });
          uv_data = this.wsMessages.map((item) => {
            return item.ir_photons;
          });
        }
        this.$nextTick(() => {
          this.setTempOptions(date, t_data);
          this.setUVOptions(date, uv_data);
        });
      },
      immediate: true,
    },
    connectionStatus: {
      handler(newStatus) {
        if (newStatus) {
          this.$message.success('webSocket连接成功');
        }
      },
    },
    messages: {
      handler() {
        let date = this.messages.map((item) => {
          return item.date.split(' ')[1];
        });
        let t_data = this.messages.map((item) => {
          return item.temperature;
        });
        let uv_data = this.messages.map((item) => {
          return item.uv;
        });
        this.$nextTick(() => {
          this.setTempOptions(date, t_data);
          this.setUVOptions(date, uv_data);
        });
      },
      deep: true,
      // immediate: true,
    },
  },
  methods: {
    /**
     * 模式设置
     */
    setMode(mode) {
      this.mode = mode;
      // this.setTempOptions();
      // this.setUVOptions();
    },
    /**
     * 获取websocket消息
     */
    async getWsMessages() {
      const params = {
        camera_id: this.currentVideo.id,
        // 当天日期 YYYY-MM-DD格式
        // date: new Date().toISOString().split('T')[0],
        date: '',
      };
      await getWebsocketMessage(params)
        .then((res) => {
          if (res.code === 200) {
            this.wsMessages = res.data;
          } else {
            this.$message.error(res.msg);
          }
        })
        .finally(() => {
          // this.setTempOptions();
          // this.setUVOptions();
          // // 只用处理最后一个就行，他是最新的
          // const lastOne = this.wsMessages[this.wsMessages.length - 1];
          // if (lastOne) {
          //   this.$nextTick(() => {
          //     this.handleAlarm(lastOne);
          //   });
          // }
        });
    },
    handleIRRules(isLabel) {
      this.isLabel = isLabel;
    },
    /**
     * 设置温度曲线options
     */
    setTempOptions(date, data) {
      // 设置title
      this.tempOptions.title = {
        text: '温度曲线',
      };
      this.tempOptions.xAxis = {
        type: 'category',
        boundaryGap: false,
        // data: this.messages.map((item) => {
        //   return item.date;
        // }),
        data: date,
      };
      this.tempOptions.yAxis = {
        type: 'value',
      };
      this.tempOptions.series = [
        {
          name: '温度',
          type: 'line',
          // data: this.messages.map((item) => {
          //   return item.temperature;
          // }),
          data: data,
        },
      ];
    },
    /**
     * 设置光子数曲线options
     */
    setUVOptions(date, data) {
      // 设置title
      this.uvOptions.title = {
        text: '光子数曲线',
      };
      this.uvOptions.xAxis = {
        type: 'category',
        boundaryGap: false,
        // data: this.messages.map((item) => {
        //   return item.date;
        // }),
        data: date,
      };
      this.uvOptions.yAxis = {
        type: 'value',
      };
      this.uvOptions.series = [
        {
          name: '光子数',
          type: 'line',
          // data: this.messages.map((item) => {
          //   return item.uv;
          // }),
          data: data,
        },
      ];
    },
    getRandomInt(min, max) {
      min = Math.ceil(min);
      max = Math.floor(max);
      return Math.floor(Math.random() * (max - min + 1)) + min;
    },
    /**
     * 处理截图
     */
    takeScreenshot(type) {
      // 调用easyplayer的截图方法
      // this.$refs.easyPlayerPro.onScreenshot();
      this.$nextTick(() => {
        this.$refs.easyPlayerPro.onAlertScreenshot(type);
      });
    },
    /**
     * 处理录像
     */
    handleRecordVideo(isRecord) {
      // 调用easyplayer的录像方法
      this.$refs.easyPlayerPro.onRecord(isRecord);
    },
  },
};
</script>

<style scoped lang="scss">
.single-media {
  width: 100%;
  height: calc(100% - 52px);
  padding: 0 10px 0 10px;
  display: flex;
  // flex-direction: column;
  background-color: #f5f5f5;
  box-sizing: border-box;
  position: relative;
  // overflow-y: auto;
}
.info {
  padding: 10px;
  span + span {
    margin-left: 20px;
  }
}
.ir-rule {
  &.active {
    color: aquamarine;
  }
}
.video-container {
  position: relative;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  // border: 1px solid #e7ececc9;
  // max-height: 100%;
  width: 100%;
  box-sizing: border-box;
  overflow: hidden; /* 防止内容溢出 */
}
.video-block-container {
  padding-bottom: 56.25%;
  width: 100%;
  position: relative;
}

.video-container .video-block {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  object-fit: cover;
  box-sizing: border-box;
}

.charts-container {
  display: flex;
  flex: 0 0 430px;
  gap: 10px;
  flex-direction: column;
  margin-left: 20px;
  box-sizing: border-box;
}
.audio-container {
  width: 100%;
  height: 100%;
  position: absolute;
  top: 0;
  left: 0;
  z-index: 9999;
}

.charts-mode {
  display: flex;
  justify-content: center;
  align-items: center;
  span {
    cursor: pointer;
    padding: 5px 20px;
    border: 1px solid #ccc;
    // border-radius: 5px;
    // margin: 0 5px;
    &.active {
      // 蓝底
      background-color: #007bff;
      border-color: #007bff;
      color: #fff;
    }
    &.item1 {
      border-right: none;
    }
    &.item2 {
      border-left: none;
    }
  }
}

.charts-item {
  flex: 1;
  display: flex;
  justify-content: center;
  align-items: center;
}

.charts-item .charts {
  width: 100%;
  height: 100%;
  object-fit: cover;
}
.charts + .charts {
  margin-top: 10px;
}
</style>
